<?php
namespace App\Http\Controllers\Business\ShopWeb\Auth;

use App\Models\ShopUser;
use App\Models\Shop;
use App\Models\SmsMessage;
use Log;
use Illuminate\Support\Facades\Redis;

class ShopWebAuth {
    //登录
    public static function login($mobile, $type, $password='', $code='') {
        if(!$mobile||(strlen($mobile)!=11)||!$type) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($type == 'password') {
            //密码登录
            $shopUser = ShopUser::where(['mobile' => $mobile, 'password' => md5($password . env('PASSWORD_SALT')), 'status' => '1'])->where('auth', '<>', '')->first();
            if ($shopUser) {
                return ['status' => 'success', 'data' => [ 'userid' => $shopUser['id'] ]];
            } else {
                return ['status' => 'failed', 'message' => '手机号或密码错误！'];
            }
        } elseif($type == 'code') {
            //验证码登录
            if(!SmsMessage::loginIdentifyingCodeVerify($mobile, $code, '5')) {
                return ['status'=>'failed', 'message'=>'验证码错误'];
            }
            $shopUserId = ShopUser::where('mobile', $mobile)->where('status', 1)->where('auth', '<>', '')->pluck('id')->first();
            if ($shopUserId) {
                return ['status' => 'success', 'data' => [ 'userid' => $shopUserId]];
            } else {
                return ['status' => 'failed', 'message' => '手机号或密码错误！'];
            }
        } else {
            return ['status'=>'failed', 'message'=>'暂没有开通'];
        }
    }
    //登录时，给手机号码发送短信
    public static function getCode($mobile) {
        if(!$mobile) {
            return ['status'=>'failed', 'message'=>'请输入手机号码'];
        }
        $isShopUser = ShopUser::where('mobile', $mobile)->where('auth', '<>', '')->where('status', '1')->first();
        if(!$isShopUser) {
            return ['status'=>'failed', 'message'=>'该手机号不是商户或者被禁用'];
        }
        $type = 5;
        $result = SmsMessage::loginIdentifyingCode($mobile, $type, '1');
        if($result == 0) {
            return ['status'=>'failed', 'message'=>'发送失败'];
        } elseif($result == 1) {
            return ['status'=>'success', 'message'=>'发送成功'];
        } elseif($result == 2) {
            return ['status'=>'failed', 'message'=>'等待60秒'];
        } else {
            return ['status'=>'failed', 'message'=>'发送失败'];
        }
    }
    //获取帐号密码
    public static function getPassword($shopUserId) {
        if(!$shopUserId) {
            return '';
        }
        $password = ShopUser::where('id', $shopUserId)->pluck('password')->first();
        return $password;
    }
    //设置密码
    public static function setPassword($shopUserId, $password, $confirmPassword) {
        if(!$shopUserId||!$password||!$confirmPassword) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($password != $confirmPassword) {
            return ['status'=>'failed', 'message'=>'两次密码不一致'];
        }
        $shopUser = ShopUser::where('id', $shopUserId)->first();
        if(!$shopUser) {
            return ['status'=>'failed', 'message'=>'获取信息错误'];
        }
        if($shopUser->password) {
            return ['status'=>'failed', 'message'=>'已经设置过密码'];
        }
        $shopUser->password = md5($password . env('PASSWORD_SALT'));
        $shopUser->save();
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //通过旧密码来修改密码
    public static function updatePasswordByOldPassword($shopUserId, $oldPassword, $password, $confirmPassword) {
        if(!$shopUserId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(!$oldPassword) {
            return ['status'=>'failed', 'message'=>'请输入原密码'];
        }
        if(!$password) {
            return ['status'=>'failed', 'message'=>'请输入新密码'];
        }
        if(!$confirmPassword) {
            return ['status'=>'failed', 'message'=>'请再次确认密码'];
        }
        if($password != $confirmPassword) {
            return ['status'=>'failed', 'message'=>'两次密码不一致'];
        }
        $shopUser = ShopUser::where('id', $shopUserId)->where('password', md5($oldPassword . env('PASSWORD_SALT')))->first();
        if(!$shopUser) {
            return ['status'=>'failed', 'message'=>'密码错误'];
        }
        $shopUser->password = md5($password . env('PASSWORD_SALT'));
        $shopUser->save();
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //通过验证码来修改密码
    public static function updatePasswordBySms($shopUserId, $code, $password, $confirmPassword) {
        if(!$shopUserId||!$code) {
            return ['status'=>'failed', 'message'=>'请输入验证码'];
        }
        if(!$password||!$confirmPassword) {
            return ['status'=>'failed', 'message'=>'请输入密码'];
        }
        if($password != $confirmPassword) {
            return ['status'=>'failed', 'message'=>'两次密码不一致'];
        }
        $shopUser = ShopUser::where('id', $shopUserId)->first();
        if(!$shopUser) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        if(!SmsMessage::loginIdentifyingCodeVerify($shopUser->mobile, $code, '5')) {
            return ['status'=>'failed', 'message'=>'验证码错误'];
        }
        $shopUser->password = md5($password . env('PASSWORD_SALT'));
        $shopUser->save();
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //是否有创建子账号，和子账号列表的权限
    public static function getCreateSubAccountAndListManageAuth($adminId, $selectShopId) {
        if(!$adminId||!$selectShopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $admin = ShopUser::where('id', $adminId)->where('auth', 'like', '%Admin%')->first();
        $selectShopIdArray = explode(',', $selectShopId);
        if($admin) {
            $isCreateSubAccountAuth = 1;
            $adminUserAuthJson =  $admin->auth;
            $adminUserAuth = json_decode($adminUserAuthJson, true);
            if(count($selectShopIdArray) > 1) {
                //多家店的时候
                $isListAuth = 0;
            } else {
                if (isset($adminUserAuth[$selectShopId]) && (in_array("Admin", $adminUserAuth[$selectShopId]))) {
                    $isListAuth = 1;
                } else {
                    $isListAuth = 0;
                }
            }
        } else {
            $isCreateSubAccountAuth = 0;
            $isListAuth = 0;
        }
        $data = [
            'iscreatesubaccountauth' => $isCreateSubAccountAuth,
            'islistauth' => $isListAuth
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //通过商家ids获取所有的帐号
    public static function getShopUsersByShopIds($shopIds) {
        if(empty($shopIds)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = [];
        $mobileLists = [];
        foreach($shopIds as $shopId) {
            $shopUsers = ShopUser::orWhere('shopid', $shopId)->orWhere('shopid', 'like', '%,' . $shopId . ',%')
                ->orWhere('shopid', 'like', $shopId . ',%')->orWhere('shopid', 'like', '%,' . $shopId)
                ->get();
            $shopName = Shop::where('id', $shopId)->pluck('name')->first();
            foreach($shopUsers as $shopUser) {
                $shopUserMobile = $shopUser->mobile;
                if(!in_array($shopUserMobile, $mobileLists)) {
                    array_push($mobileLists, $shopUserMobile);
                } else {
                    continue;
                }
                $list = [
                    'shopuserid' => $shopUser->id,
                    'shopusername' => $shopUser->name,
                    'shopusermobile' => $shopUserMobile,
                    'shopname' => $shopName,
                    'shopid' => $shopId,
                    'status' => $shopUser->status,
                ];
                array_push($data, $list);
            }
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //通过单一门店id获取所有的子帐号,过滤掉自己
    public static function getAllSubAccountByShopId($shopId, $shopUserId, $adminShopIds) {
        if(!$shopId||!$shopUserId||empty($adminShopIds)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = [];
        $GLOBALS['shopId'] = $shopId;
        $shopUsers = ShopUser::where('id', '<>', $shopUserId)
            ->where(function($query) {
                $query->orWhere('shopid', $GLOBALS['shopId'])->orWhere('shopid', 'like', '%,' . $GLOBALS['shopId'] . ',%')
                    ->orWhere('shopid', 'like', $GLOBALS['shopId'] . ',%')->orWhere('shopid', 'like', '%,' . $GLOBALS['shopId']);
            })
            ->orderBy('updated_at', 'desc')
            ->get();
        $shopName = Shop::where('id', $shopId)->pluck('name')->first();
        foreach($shopUsers as $shopUser) {
            $shopUserMobile = $shopUser->mobile;
            $shopUserShopId = $shopUser->shopid;
            $shopUserShopIdArray = explode(',', $shopUserShopId);
            $shopCount = 0;
            foreach($shopUserShopIdArray as $shopIdList) {
                if(in_array($shopIdList, $adminShopIds)) {
                    ++$shopCount;
                }
            }
            //没有存在该手机号码
            $list = [
                'shopuserid' => $shopUser->id,
                'shopusername' => $shopUser->name,
                'shopusermobile' => $shopUserMobile,
                'shopname' => $shopName,
                'shopcount' => $shopCount,
                'shopid' => $shopId,
                'status' => $shopUser->status,
            ];
            $data[$shopUserMobile] = $list;
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //新增子帐号时获取验证码
    public static function getCodeBeforeAddSubAccount($mobile, $auth) {
        if(!$mobile) {
            return ['status'=>'failed', 'message'=>'请输入手机号码'];
        }
        if(empty($auth)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        //判断是否已经是这家店的管理人员
        $shopCount = 0;
        $firstShopId = '';
        foreach($auth as $k=>$v) {
            if(!in_array("Admin", $v)) {
                continue;
            }
            $GLOBALS['searchShopId'] = $k;
            $isThisShopUser = ShopUser::where('mobile', $mobile)->where(function($query) {
                $query->orWhere('shopid', $GLOBALS['searchShopId'])
                    ->orWhere('shopid', 'like', '%,' . $GLOBALS['searchShopId'] . ',%')
                    ->orWhere('shopid', 'like', $GLOBALS['searchShopId'] . ',%')
                    ->orWhere('shopid', 'like', '%,' . $GLOBALS['searchShopId']);
            })->get()->count();
            if($isThisShopUser > 0) {
                ++$shopCount;
            }
            if($firstShopId == '') {
                $firstShopId = $k;
            }
        }
        if($shopCount == 1) {
            $shopName = Shop::where('id', $firstShopId)->pluck('name')->first();
            $message = "此手机号在".$shopName."店创建过子账号了,请在".$shopName."店的子账号列表使用编辑功能";
            return ['status'=>'failed', 'message'=>$message];
        } elseif($shopCount>1) {
            $shopName = Shop::where('id', $firstShopId)->pluck('name')->first();
            if($shopCount == 2) {
                $showShopCount = "二";
            } elseif($shopCount == 3) {
                $showShopCount = "三";
            } elseif($shopCount == 4) {
                $showShopCount = "四";
            } elseif($shopCount == 5) {
                $showShopCount = "五";
            } else {
                $showShopCount = "";
            }
            $message = "此手机号在".$shopName."等".$showShopCount."家店创建过子账号了,请在".$shopName."等".$showShopCount."家店的子账号列表使用编辑功能";
            return ['status'=>'failed', 'message'=>$message];
        }
        $type = 5;
        $result = SmsMessage::loginIdentifyingCode($mobile, $type, '1');
        if($result == 0) {
            return ['status'=>'failed', 'message'=>'发送失败'];
        } elseif($result == 1) {
            return ['status'=>'success', 'message'=>'发送成功'];
        } elseif($result == 2) {
            return ['status'=>'failed', 'message'=>'等待60秒'];
        } else {
            return ['status'=>'failed', 'message'=>'发送失败'];
        }
    }
    //新增子账号
    public static function addSubAccount($adminId, $mobile, $name, $auth, $code, $shopIds) {
        if(!$adminId||!$code||!$mobile||!$name||empty($shopIds)) {
            return ['status'=>'failed', 'message'=>'请勾选门店权限'];
        }
        //验证短信验证码
        if(!SmsMessage::loginIdentifyingCodeVerify($mobile, $code, '5')) {
            return ['status'=>'failed', 'message'=>'验证码错误'];
        }
        //权限
        $admin = ShopUser::where('id', $adminId)->where('auth', 'like', '%Admin%')->first();
        if(!$admin) {
            return ['status'=>'failed', 'message'=>'你不是管理人员，权限不够'];
        }
        $adminAuthJson = $admin->auth;
        $adminShopId = $admin->shopid;
        $adminShopIdArray = explode(',', $adminShopId);
        $adminAuthArray = json_decode($adminAuthJson, true);
        $authArray = json_decode($auth, true);
        $shopIdString = '';
        foreach($authArray as $k => $v) {
            if(empty($adminShopIdArray) || !in_array($k, $adminShopIdArray) || !isset($adminAuthArray[$k])||!in_array('Admin', $adminAuthArray[$k])) {
                return ['status'=>'failed', 'message'=>'你不是这家店的管理人员，权限不够'];
            }
            $shopIdString .= $k . ',';
        }
        //判断是否已经是这家店的管理人员
        foreach($shopIds as $k) {
            $GLOBALS['searchShopId'] = $k;
            $isThisShopUser = ShopUser::where('mobile', $mobile)->where(function($query) {
                $query->orWhere('shopid', $GLOBALS['searchShopId'])
                    ->orWhere('shopid', 'like', '%,' . $GLOBALS['searchShopId'] . ',%')
                    ->orWhere('shopid', 'like', $GLOBALS['searchShopId'] . ',%')
                    ->orWhere('shopid', 'like', '%,' . $GLOBALS['searchShopId']);
            })->get()->count();
            if($isThisShopUser > 0) {
                return ['status'=>'failed', 'message'=>'该帐号已经是该商家的管理人员'];
            }
        }
        //创建帐号，或者给老用户新增门店权限
        $shopIdString = rtrim($shopIdString, ',');
        $oldShopUser = ShopUser::where('mobile', $mobile)->first();
        if(!$oldShopUser) {
            //新用户
            $shopUser = ShopUser::create([
                'mobile' => $mobile,
                'name' => $name,
                'auth' => $auth,
                'shopid' => $shopIdString
            ]);
            $shopUser->save();
            //修改shops表
            $childShopIdArray = explode(',', $shopIdString);
            foreach($childShopIdArray as $childShopId) {
                $childShop = Shop::where('id', $childShopId)->first();
                $childMobileArray = [];
                if(isset($childShop['childmobile']) && ($childShop['childmobile'] != '')) {
                    $childMobileArray = json_decode($childShop['childmobile'], true);
                    if(!in_array($mobile, $childMobileArray)) {
                        array_push($childMobileArray, $mobile);
                    }
                }
                if(!empty($childMobileArray)) {
                    $childShop->childmobile = json_encode($childMobileArray);
                    $childShop->save();
                }
            }
        } else {
            //已经开通过
            $oldShopUserId = $oldShopUser->id;
            $oldShopUserAuthJson = $oldShopUser->auth;
            $oldShopId = $oldShopUser->shopid;
            $oldShopUserAuthArray = json_decode($oldShopUserAuthJson, true);
            if(!is_array($oldShopUserAuthArray)) {
                //之前是否有商家权限
                $oldShopUserAuthArray = $authArray;
                $oldShopIdString = $shopIdString;
            } else {
                //把新增的权限加进去
                foreach ($authArray as $k => $v) {
                    $oldShopUserAuthArray[$k] = $v;
                }
                //把商家id 加进去
                $oldShopIdString = $oldShopId . ',' . $shopIdString;
            }
            $oldShopUser->name = $name;
            $oldShopUser->shopid = $oldShopIdString;
            $oldShopUser->auth = json_encode($oldShopUserAuthArray);
            $oldShopUser->save();
            //修改shops表
            $childShopIdArray = explode(',', $oldShopIdString);
            foreach($childShopIdArray as $childShopId) {
                $childShop = Shop::where('id', $childShopId)->first();
                $childMobileArray = [];
                if(isset($childShop['childmobile']) && ($childShop['childmobile'] != '')) {
                    $childMobileArray = json_decode($childShop['childmobile'], true);
                    if(!in_array($mobile, $childMobileArray)) {
                        array_push($childMobileArray, $mobile);
                    }
                }
                if(!empty($childMobileArray)) {
                    $childShop->childmobile = json_encode($childMobileArray);
                    $childShop->save();
                }
            }
            //刷新redis
            Redis::del('ShopAuth:'.$oldShopUserId);
        }
        return ['status'=>'success', 'message'=>'新增成功'];
    }
    //获取子账号信息
    public static function getSubAccount($adminId, $subAccountId, $adminShopIds) {
        if(!$adminId||!$subAccountId||empty($adminShopIds)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        //权限
        $admin = ShopUser::where('id', $adminId)->where('auth', 'like', '%Admin%')->first();
        if(!$admin) {
            return ['status'=>'failed', 'message'=>'你不是管理人员，权限不够'];//TODO 多门店权限不一样没有处理
        }
        $adminAuthJson = $admin->auth;
        $adminAuth = json_decode($adminAuthJson, true);
        $data = ShopUser::where('id', $subAccountId)
            ->select('id as shopuserid', 'name as shopusername', 'mobile as shopusermobile', 'shopid', 'auth', 'status')
            ->first();
        if(!$data) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $shopIdString = $data->shopid;
        $shopIdArray = explode(',', $shopIdString);
        $shopLists = [];
        foreach($adminAuth as $k => $adminAuthList) {
            if(!in_array("Admin", $adminAuthList)) {
                continue;
            }
            $shopList = Shop::where('id', $k)->whereIn('id', $shopIdArray)->select('id as shopid', 'name as shopname', 'address', 'parentmobile')->first();
            if($shopList) {
                array_push($shopLists, [
                    'shopid' => $shopList['shopid'],
                    'shopname' => $shopList['shopname'],
                    'address' => $shopList['address'],
                    'parentmobile' => $shopList['parentmobile']
                ]);
            }
        }
        $authJson = $data['auth'];
        $authArray = json_decode($authJson, true);
        foreach($shopLists as $k => $v ) {
            if(isset($authArray[$v['shopid']])) {
                $shopLists[$k]['authlists'] = $authArray[$v['shopid']];
            } else {
                $shopLists[$k]['authlists'] = [];
            }
        }
        $data['shoplists'] = $shopLists;
        return ['status'=>'success', 'data'=>$data];
    }
    //获取子帐号权限
    public static function getSubAccountAuth($adminId, $subAccountId) {
        if(!$adminId||!$subAccountId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        //权限
        $admin = ShopUser::where('id', $adminId)->where('auth', 'like', '%Admin%')->first();
        if(!$admin) {
            return ['status'=>'failed', 'message'=>'你不是管理人员，权限不够'];//TODO 多门店权限不一样没有处理
        }
        $auth = ShopUser::where('id', $subAccountId)->pluck('auth')->first();
        if(!$auth) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $adminShopIdString = $admin->shopid;
        $adminShopIdArray = explode(',', $adminShopIdString);
        $authArray = json_decode($auth, true);
        $data = [];
        foreach($adminShopIdArray as $shopId ) {
            if(isset($authArray[$shopId])) {
                 $data[$shopId] = $authArray[$shopId];
            }
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //在即将编辑获取子账号信息
    public static function getSubAccountBeforeEdit($adminId, $subAccountId, $adminShopIds) {
        if(!$adminId||!$subAccountId||empty($adminShopIds)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        //权限
        $admin = ShopUser::where('id', $adminId)->where('auth', 'like', '%Admin%')->first();
        if(!$admin) {
            return ['status'=>'failed', 'message'=>'你不是管理人员，权限不够'];//TODO 多门店权限不一样没有处理
        }
        $data = ShopUser::where('id', $subAccountId)
            ->select('id as shopuserid', 'name as shopusername', 'mobile as shopusermobile', 'shopid', 'auth', 'status')
            ->first();
        if(!$data) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $adminAuthJson = $admin->auth;
        $adminAuth = json_decode($adminAuthJson, true);
        $shopLists = [];
        $authJson = $data->auth;
        $authArray = json_decode($authJson, true);
        foreach($adminAuth as $k=>$v) {
            if(in_array("Admin", $v)) {
                $shopList = Shop::where('id', $k)->select('id as shopid', 'name as shopname', 'address', 'parentmobile')->first();
                if(isset($authArray[$k])) {
                    $authLists = $authArray[$k];
                } else {
                    $authLists = [];
                }
                if($shopList) {
                    array_push($shopLists, [
                        'shopid' =>$shopList['shopid'],
                        'shopname' =>$shopList['shopname'],
                        'address' => $shopList['address'],
                        'parentmobile' => $shopList['parentmobile'],
                        'authlists' => $authLists
                     ]);
                }
            }
        }
        $data['shoplists'] = $shopLists;
        return ['status'=>'success', 'data'=>$data];
    }
    //编辑子账号
    public static function updateSubAccount($adminId, $subAccountId, $auth) {
        if(!$adminId||!$subAccountId) {
            return ['status'=>'failed', 'message'=>'请勾选门店权限'];
        }
        //权限
        $admin = ShopUser::where('id', $adminId)->where('auth', 'like', '%Admin%')->first();
        if(!$admin) {
            return ['status'=>'failed', 'message'=>'你不是管理人员，权限不够'];
        }
        $adminAuthJson = $admin->auth;
        $adminShopId = $admin->shopid;
        $adminShopIdArray = explode(',', $adminShopId);
        $adminAuthArray = json_decode($adminAuthJson, true);
        $authArray = json_decode($auth, true);
        $shopIdString = '';
        foreach($authArray as $k => $v) {
            if(empty($adminShopIdArray) || !in_array($k, $adminShopIdArray) || !isset($adminAuthArray[$k])||!in_array('Admin', $adminAuthArray[$k])) {
                return ['status'=>'failed', 'message'=>'你不是这家店的管理人员，权限不够'];
            }
            $shopIdString .= $k . ',';
        }
        //创建帐号，或者给老用户新增门店权限
        $shopIdString = rtrim($shopIdString, ',');
        $oldShopUser = ShopUser::where('id', $subAccountId)->first();
        if(!$oldShopUser) {
            return ['status'=>'failed', 'message'=>'你不是管理人员，权限不够'];
        }
        //已经开通过
        $oldShopUserAuthJson = $oldShopUser->auth;
        $oldShopId = $oldShopUser->shopid;
        $oldShopUserMobile = $oldShopUser->mobile;
        $oldShopUserAuthArray = json_decode($oldShopUserAuthJson, true);
        if(!is_array($oldShopUserAuthArray)) {
            //权限为空
            $oldShopUserAuthArray = $authArray;
            $oldShopIdString = $shopIdString;
            $deleteShopIdArray = []; //要删除的
            $keepShopIdString = '';
        } else {
            $deleteShopIdString = '';
            $keepShopIdString = ''; //不是该些门店管理下的门店id,需要继续保留下来
            $shopIdArray = explode(',', $shopIdString);
            $oldShopIdArray = explode(',', $oldShopId);
            foreach($oldShopIdArray as $oldShopIdList) {
                if(!in_array($oldShopIdList, $adminShopIdArray)) {
                    //这些id不属于管理人员所管理的shopid中
                    $keepShopIdString .= $oldShopIdList . ',';
                } else {
                    if(!in_array($oldShopIdList, $shopIdArray)) {
                        $deleteShopIdString .= $oldShopIdList . ',';
                    }
                }
            }
            $keepShopIdString = rtrim($keepShopIdString, ',');
            $deleteShopIdString = rtrim($deleteShopIdString, ',');
            $oldShopIdString = $shopIdString . ',' . $keepShopIdString ;
            $oldShopIdString = rtrim($oldShopIdString, ',');
            //有其他门店权限
            foreach ($authArray as $k => $v) {
                $oldShopUserAuthArray[$k] = $v;
            }
            if($deleteShopIdString != '') {
                $deleteShopIdArray = explode(',', $deleteShopIdString);
                //删除权限
                foreach($deleteShopIdArray as $deleteShopIdList) {
                    unset($oldShopUserAuthArray[$deleteShopIdList]);
                }
            } else {
                $deleteShopIdArray = [];
            }
        }
        $oldShopUser->shopid = $oldShopIdString;
        $oldShopUser->auth = json_encode($oldShopUserAuthArray);
        $oldShopUser->save();
        //修改shops表
        //新增的shopid
        $childShopIdArray = explode(',', $oldShopIdString);
        foreach($childShopIdArray as $childShopId) {
            $childShop = Shop::where('id', $childShopId)->first();
            $childMobileArray = [];
            if(isset($childShop['childmobile']) && ($childShop['childmobile'] != '')) {
                $childMobileArray = json_decode($childShop['childmobile'], true);
                if(!in_array($oldShopUserMobile, $childMobileArray)) {
                    array_push($childMobileArray, $oldShopUserMobile);
                }
            }
            if(!empty($childMobileArray)) {
                $childShop->childmobile = json_encode($childMobileArray);
                $childShop->save();
            }
        }
        //已删除的shopid
        if(count($deleteShopIdArray)>0) {
            foreach($deleteShopIdArray as $deleteShopId) {
                $deleteShop = Shop::where('id', $deleteShopId)->first();
                if(isset($childShop['childmobile']) && ($childShop['childmobile'] != '')) {
                    $childMobileArray = json_decode($childShop['childmobile'], true);
                    if(in_array($oldShopUserMobile, $childMobileArray)) {
                        unset($childMobileArray[array_search($oldShopUserMobile,$childMobileArray)]);
                        $deleteShop->childmobile = json_encode($childMobileArray);
                        $deleteShop->save();
                    }
                }
            }
        }
        //刷新redis
        Redis::del('ShopAuth:'.$subAccountId);
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //通过shopIds获取商家信息
    public static function getShopDetailsByShopIds($shopIds, $adminUserAuth) {
        if(empty($shopIds) || empty($adminUserAuth)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = [];
        foreach($adminUserAuth as $k=>$v) {
            if(in_array("Admin", $v)) {
                $list = Shop::where('id', $k)->select('id as shopid', 'name as shopname')->first();
                array_push($data, $list);
            }
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //通过手机号码获取该手机下的商家ids
    public static function getShopIdsByMobile($mobile) {
        if(!$mobile) {
            return ['status' => 'failed', 'message'=>'参数错误'];
        }
        $shopId = ShopUser::where('mobile', $mobile)->pluck('shopid')->first();
        if(!$shopId) {
            return ['status'=>'success', 'data'=>[]];
        }
        $data = explode(',', $shopId);
        return ['status'=>'success', 'data'=>$data];
    }
    //停用子帐号
    public static function disableSubAccount($adminId, $subAccountId, $shopId) {
        if(!$adminId|| !$subAccountId||!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        //权限
        $admin = ShopUser::where('id', $adminId)->where('auth', 'like', '%Admin%')->first();
        if(!$admin) {
            return ['status'=>'failed', 'message'=>'你不是管理人员，权限不够'];
        }
        $adminAuthJson = $admin->auth;
        $adminShopId = $admin->shopid;
        $adminShopIdArray = explode(',', $adminShopId);
        $adminAuthArray = json_decode($adminAuthJson, true);
        $oldShopUser = ShopUser::where('id', $subAccountId)->first();
        if(!$oldShopUser) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $auth = $oldShopUser->auth;
        $mobile = $oldShopUser->mobile;
        $authArray = json_decode($auth, true);
        $oldShopIdString = $oldShopUser->shopid;
        $oldShopIdArray = explode(',', $oldShopIdString);
        if (empty($adminShopIdArray) || !in_array($shopId, $adminShopIdArray) || !isset($adminAuthArray[$shopId]) || !in_array('Admin', $adminAuthArray[$shopId])) {
            return ['status' => 'failed', 'message' => '你不是这家店的管理人员，权限不够'];
        }
        unset($authArray[$shopId]);
        foreach($oldShopIdArray as $k=>$v) {
            if($v == $shopId) {
                unset($oldShopIdArray[$k]);
            }
        }
        $shopIdString = implode(',', $oldShopIdArray);//数组变字符串
        $oldShopUser->shopid = $shopIdString;
        $oldShopUser->auth = json_encode($authArray);
        $oldShopUser->save();
        //修改shops表
        $shop = Shop::where('id', $shopId)->first();
        if($shop) {
            $childMobile = $shop->childmobile;
            $childMobileArray = json_decode($childMobile, true);
            if(count($childMobileArray) > 0) {
                foreach($childMobileArray as $k=>$v) {
                    if($v == $mobile) {
                        unset($childMobileArray[$k]);
                        $shop->childmobile = json_encode($childMobileArray);
                        $shop->save();
                    }
                }
            }
        }
        //刷新redis
        Redis::del('ShopAuth:'.$subAccountId);
        return ['status'=>'success', 'message'=>'禁用成功'];
    }
}
